﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebServiceTMS.Helpers;

namespace WebServiceTMS.Controllers
{
    public class LoginData
    {
        public string Id { get; set; }
        public string NS { get; set; }
        public string Status { get; set; }
    }
    public class LoginController : ApiController
    {
        //POST api/Login/AuthorizeUser
        [HttpPost]
        [ActionName("AuthorizeUser")]
        public HttpResponseMessage AuthorizeUser(HttpRequestMessage request)
        {
            try
            {
                var content = request.Content;
                var jsonContent = content.ReadAsStringAsync().Result;

                var userObject = JObject.Parse(jsonContent);

                var tmp = new Dictionary<string, string>();
                foreach (KeyValuePair<String, JToken> resp in userObject)
                {
                    tmp.Add(resp.Key, resp.Value.ToString());
                }

                if (tmp.Count > 0)
                {
                    string login = null;
                    bool isSuccessEmail = tmp.TryGetValue("Login", out login);
                    string password = null;
                    bool isSuccessPassword = tmp.TryGetValue("Password", out password);

                    if (isSuccessEmail && isSuccessPassword)
                    {
                        return UserAuthentication(login, password);
                    }
                    return HttpResponseHelper.CreateHttpResponse("error", "Parameters parsing error");
                }
                return HttpResponseHelper.CreateHttpResponse("error", "Parameters list is empty");
            }
            catch (Exception ex)
            {
                return HttpResponseHelper.CreateHttpResponse("server_error", ex.Message);
            }
        }

        private HttpResponseMessage UserAuthentication(string login, string password)
        {
            try
            {
                using (var context=new TMSEntities())
                {
                    var user = context.Users.FirstOrDefault(u => u.Login == login);

                    if (user != null)
                    {
                        using (var md5Hash = MD5.Create())
                        {
                            var passWithSalt = password + user.Salt;
                            if (StringGenerator.VerifyMd5Hash(md5Hash, passWithSalt, user.Password))
                            {
                                var loginData = new LoginData
                                {
                                    Id = TMSCryptography.Encrypt(user.Id.ToString()),
                                    NS = user.Name + "~" + user.Surname,
                                    Status = user.Status
                                };
                                return HttpResponseHelper.CreateHttpResponse("success", JsonConvert.SerializeObject(loginData));
                            }
                            return HttpResponseHelper.CreateHttpResponse("error", "Wrong password");
                        }
                    }
                    return HttpResponseHelper.CreateHttpResponse("error", "User not found.");
                }
            }
            catch (Exception ex)
            {
                return HttpResponseHelper.CreateHttpResponse("server_error", ex.Message);
            }
        }
    }
}
